//
//  Team9XioalLeiViewController.m
//  Team9Project
//
//  Created by 朱嘉祺 on 15/10/22.
//  Copyright © 2015年 apple. All rights reserved.
//

#import "Team9XioalLeiViewController.h"
#import "JQAFNetworkTool.h"
#import "Team9XiaoLeiModel.h"
#import "Team9ShowCityModel.h"
#import <CoreLocation/CoreLocation.h>
#import "Team9BaseTableViewCell.h"

#define WID 375.0

@interface Team9XioalLeiViewController ()<UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate>

@property (nonatomic, strong) UITableView *locationTableView;
@property (nonatomic, strong) NSMutableArray *show_cityArr;
@property (nonatomic, strong) NSMutableArray *hot_zoneArr;
@property (nonatomic, strong) NSMutableArray *city_listArr;
@property (nonatomic, strong) NSArray *arr;
@property (nonatomic, copy) NSString *uId;
@property (nonatomic, copy) NSString *str;
@property (nonatomic, copy) NSString *cityStr;
@property (nonatomic,strong) CLLocationManager *locationManager;
@property (nonatomic, assign) BOOL isSelect;

@property (nonatomic, assign) NSInteger oldSeclect;
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, copy) NSString *buttonTitle;

@end

@implementation Team9XioalLeiViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.locationManager startUpdatingLocation];
    [self locationCity];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.locationManager stopUpdatingLocation];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.url = @"http://api.meilijia.com/app/advanced_pro_zone_list";
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.locationTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEGHT - 64) style:UITableViewStyleGrouped];
    self.locationTableView.delegate = self;
    self.locationTableView.dataSource = self;
    self.locationTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.locationTableView];

    self.uId = @"";
    self.show_cityArr = [NSMutableArray array];
    self.hot_zoneArr = [NSMutableArray array];
    self.cityStr = @"";

    self.locationTableView.bounces = NO;

    [self createData];


}

- (void)createData{
    [JQAFNetworkTool getUrl:@"http://api.meilijia.com/app/advanced_pro_zone_list" body:nil result:JQJSON headerFile:nil success:^(id result) {
        
        NSDictionary *dic = result[@"data"][@"advanced_pro_zone_list"];
        self.show_cityArr = [Team9XiaoLeiModel baseModelByArr:dic[@"show_city"]].mutableCopy;
        self.hot_zoneArr = [Team9XiaoLeiModel baseModelByArr:dic[@"hot_zone"]].mutableCopy;

        [self.locationTableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}




- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.show_cityArr.count + 3;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(0, 0, WIDTH, 44 / WID * WIDTH);
        [button setTitle:@"当前城市" forState:UIControlStateNormal];
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 10 / WID * WIDTH, 0, 285 / WID * WIDTH);
        [button addTarget:self action:@selector(first:) forControlEvents:UIControlEventTouchUpInside];
        UIColor *color;
        if ([Team9EveningType shareEvening].eveningFailling) {
            color = [UIColor whiteColor];
        } else color = [UIColor blackColor];
        [button setTitleColor:color forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:18 / WID * WIDTH];
        return button;
    }else if (section == 1){
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(0, 0, WIDTH, 44 / WID * WIDTH);
        [button setTitle:@"全部城市" forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:18 / WID * WIDTH];
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 10 / WID * WIDTH, 0, 285 / WID * WIDTH);
        button.tag = section;
        [button addTarget:self action:@selector(first:) forControlEvents:UIControlEventTouchUpInside];
        UIColor *color;
        if ([Team9EveningType shareEvening].eveningFailling) {
            color = [UIColor whiteColor];
        } else color = [UIColor blackColor];
        [button setTitleColor:color forState:UIControlStateNormal];
        return button;

    }else if (section == 2){
        UIButton *button
        = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(0, 0, WIDTH, 44 / WID * WIDTH);
       [button setTitle:@"热门城市" forState:UIControlStateNormal];
        button.tag = section;
        button.titleLabel.font = [UIFont systemFontOfSize:18 / WID * WIDTH];
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 10 / WID * WIDTH, 0, 285 / WID * WIDTH);
        [button addTarget:self action:@selector(first:) forControlEvents:UIControlEventTouchUpInside];
        UIColor *color;
        if ([Team9EveningType shareEvening].eveningFailling) {
            color = [UIColor whiteColor];
        } else color = [UIColor blackColor];
        [button setTitleColor:color forState:UIControlStateNormal];
        return button;
    }else if (section > 2 && section < self.show_cityArr.count + 3){
        Team9ShowCityModel *model = self.show_cityArr[section - 3];
        UIButton *button
        = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tag = section;
        button.frame = CGRectMake(0, 0, WIDTH, 44 / WID * WIDTH);
        button.titleLabel.font = [UIFont systemFontOfSize:18 / WID * WIDTH];
        [button setTitle:model.name forState:UIControlStateNormal];
        if (model.name.length == 2) {
            button.titleEdgeInsets = UIEdgeInsetsMake(0, 10 / WID * WIDTH, 0, 325 / WID * WIDTH);
        }else{
            button.titleEdgeInsets = UIEdgeInsetsMake(0, 10 / WID * WIDTH, 0, 305 / WID * WIDTH);
        }
        [button addTarget:self action:@selector(first:) forControlEvents:UIControlEventTouchUpInside];
        UIColor *color;
        if ([Team9EveningType shareEvening].eveningFailling) {
            color = [UIColor whiteColor];
        } else color = [UIColor blackColor];
        [button setTitleColor:color forState:UIControlStateNormal];
        return button;
    }

    return nil;
}

- (void)first:(UIButton *)button{
    if ([button.titleLabel.text isEqualToString:self.buttonTitle]) {
        self.isSelect = !self.isSelect;
    }else{
        self.isSelect = YES;
        self.buttonTitle = button.titleLabel.text;
    }

   
    [self.locationTableView beginUpdates];
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:button.tag];
    [self.locationTableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
        if (self.oldSeclect) {
            NSIndexSet *oldSet = [NSIndexSet indexSetWithIndex:self.oldSeclect];
            [self.locationTableView reloadSections:oldSet withRowAnimation:UITableViewRowAnimationFade];
        }
    
    [self.locationTableView endUpdates];
    
    if (self.isSelect && self.show_cityArr.count) {
                    [self.locationTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:button.tag] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            self.oldSeclect = button.tag;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 1;
    }else if (section == 2){
        if (self.isSelect && [self.buttonTitle isEqualToString:@"热门城市"]){
            return self.hot_zoneArr.count;
        }else{
            return 0;
        }
    }else if(section > 2 && section < self.show_cityArr.count + 3){
        Team9XiaoLeiModel *model = self.show_cityArr[section - 3];
        if (self.isSelect && [self.buttonTitle isEqualToString:model.name]) {
            self.city_listArr = (NSMutableArray *)model.city_list;
        }else{
            self.city_listArr =[NSMutableArray array];
        }
//        NSLog(@"self.city_listArr.count%ld", self.city_listArr.count);
        return self.city_listArr.count;
    }
    return 0;
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44.0f / WID * WIDTH;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *reuse = @"reuse";
    Team9BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[Team9BaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        [cell changecolor];
    }
    
    if (indexPath.section == 0) {
        if ([self.cityStr isEqualToString:@""]) {
            cell.textLabel.text = @"GPS定位";
        }else{
            NSString *city = [self.cityStr stringByReplacingOccurrencesOfString:@"市" withString:@""];
            cell.textLabel.text = city;
            [self.locationManager stopUpdatingLocation];
        }
       
    }else if (indexPath.section == 1){
        cell.textLabel.text = @"全部";
    }else if (indexPath.section == 2) {
        Team9XiaoLeiModel *model = self.hot_zoneArr[indexPath.row];
        cell.textLabel.text = model.name;
    }else if (indexPath.section > 2 && indexPath.section < self.show_cityArr.count + 3){
        
        Team9XiaoLeiModel *model = self.show_cityArr[indexPath.section - 3];
        self.city_listArr = (NSMutableArray *)model.city_list;
        cell.textLabel.text = self.city_listArr[indexPath.row][@"name"];

    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = [self.cityStr stringByReplacingOccurrencesOfString:@"市" withString:@""];
    if (indexPath.section == 0) {
        for (Team9XiaoLeiModel *model in self.show_cityArr) {
            for (NSMutableDictionary *dic in (NSMutableArray *)model.city_list) {
                //遍历找到定位城市对应的id
                if ([str isEqualToString:dic[@"name"]]) {
//                    NSLog(@"传东西%@", dic[@"name"]);
                    self.uId = [NSString stringWithFormat:@"%@",dic[@"id"]];
                }
            }
        }
        //如果在在详细城市中没找到 去热门城市中找id
        if ([self.uId isEqualToString:@""]) {
            
            for (Team9XiaoLeiModel *model in self.hot_zoneArr) {
                if ([str isEqualToString:model.name]) {
//                    NSLog(@"%ld",model.id);
                }
            }
        }
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:self.uId forKey:@"uId"];
        [dic setObject:str forKey:@"modelname"];
        if (![str isEqualToString:@""]) {
             [[NSNotificationCenter defaultCenter] postNotificationName:@"sendData" object:nil userInfo:dic];
        }
        [self.navigationController popViewControllerAnimated:YES];
        
#pragma 全部城市点击方法
    }else if (indexPath.section ==1){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sendData" object:nil userInfo:nil];
        [self.navigationController popViewControllerAnimated:YES];
        NSLog(@"123");
    }else if(indexPath.section == 2){
        Team9XiaoLeiModel *model = self.hot_zoneArr[indexPath.row];
        NSString *str1 = [NSString stringWithFormat:@"%ld", model.id];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:str1 forKey:@"uId"];
        [dic setObject:model.name forKey:@"modelname"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sendData" object:nil userInfo:dic];
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        Team9XiaoLeiModel *model = self.show_cityArr[indexPath.section-3];
        NSMutableArray *arr = (NSMutableArray *)model.city_list;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:arr[indexPath.row][@"id"] forKey:@"uId"];
        [dic setObject:arr[indexPath.row][@"name"] forKey:@"modelname"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sendData" object:nil userInfo:dic];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}


-(void)locationCity{
    //判断定位操作是否被允许
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        // 3. 定位精度
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        _locationManager.distanceFilter =kCLDistanceFilterNone;
        // 4.请求用户权限：分为：?只在前台开启定位?在后台也可定位，
        //注意：建议只请求?和?中的一个，如果两个权限都需要，只请求?即可，
        //??这样的顺序，将导致bug：第一次启动程序后，系统将只请求?的权限，?的权限系统不会请求，只会在下一次启动应用时请求?
        if ([[[UIDevice currentDevice] systemVersion] floatValue]<8) {
            
        }
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
            //[_locationManager requestWhenInUseAuthorization];//?只在前台开启定位
            [_locationManager requestAlwaysAuthorization];//?在后台也可定位
        }
        // 5.iOS9新特性：将允许出现这种场景：同一app中多个location manager：一些只能在前台定位，另一些可在后台定位（并可随时禁止其后台定位）。
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
            _locationManager.allowsBackgroundLocationUpdates = YES;
        }
        [_locationManager startUpdatingLocation];
        
    }else {
        //提示用户无法进行定位操作
    }
    // 6. 更新用户位置
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:self.locationManager.location
        completionHandler:^(NSArray *placemarks, NSError *error) {
            for (CLPlacemark *place in placemarks) {
                UILabel *label = (UILabel *)[self.view viewWithTag:101];
                label.text = place.name;
                NSLog(@"name,%@", place.name); // 位置名
        // NSLog(@"thoroughfar,%@",place.thoroughfare);
        // 街道
        //NSLog(@"subThoroughfare,%@",place.subThoroughfare);
        // 子街道
            NSLog(@"locality,%@",place.locality);
                self.cityStr = place.locality;
        [self.locationTableView reloadData];
   // 市   NSLog(@"subLocality,%@",place.subLocality);
   // 区   NSLog(@"country,%@",place.country);
   // 国家
            }
                       
        }];
    
}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    
    if (error.code == kCLErrorDenied) {
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
        NSLog(@"%@",error);
    }
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
